﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VideoCarousel.Tool
{
    public class VideoGetTime
    {
        public static TimeSpan GetVideoTime(string ffmpgeFileName,string videoFileName)
        {
            string ffmpeg = ffmpgeFileName;
            string arg = $"-i \"{videoFileName}\"";
            System.Diagnostics.ProcessStartInfo processStartInfo = new System.Diagnostics.ProcessStartInfo();
            processStartInfo.FileName = ffmpeg;
            processStartInfo.Arguments = arg;
            processStartInfo.RedirectStandardOutput = false;
            processStartInfo.RedirectStandardError = true;
            processStartInfo.UseShellExecute = false;
            processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            System.Diagnostics.Process process = new System.Diagnostics.Process();

            process.StartInfo = processStartInfo;
            process.Start();
            using (var standardOutPut = process.StandardError)
            {
                string str = standardOutPut.ReadToEnd();
                string d = "Duration: ";
                int durationIndex = str.IndexOf(d);
                var durationStr = str.Substring(durationIndex + d.Length);
                int startIndex = durationStr.IndexOf(", start: ");
                var time = durationStr.Substring(0, startIndex);
                TimeSpan t = TimeSpan.ParseExact(time, "hh\\:mm\\:ss\\.ff", CultureInfo.InvariantCulture);
                return t;
            }
        }
    }
}
